<template>
  <el-form :disabled="disabled" inline>
    <el-cascader :props="props" @change="change" />
  </el-form>
</template>

<script lang="ts" setup>
import { useCategoryStore } from "@/stores/category";
import type { CascaderProps, CascaderValue } from "element-plus";
const categoryStore = useCategoryStore(); // 实例化仓库
defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
});
// 进行三级列表的选择后触发，更改category3Id的值
const change = async function (val: CascaderValue) {
  if (Array.isArray(val) && val.length > 0) {
    categoryStore.category3Id = val[2] as number;
  }
};
const props: CascaderProps = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level, value } = node;
    // level 为级联选择器的层级，值为0或1或……等等。
    // value 为选择的id值
    if (level === 0) {
      await categoryStore.getCategory1ListAction();
      const nodes = categoryStore.category1List.map((item) => ({
        value: item.id,
        label: item.name,
      }));
      resolve(nodes);
    } else if (level === 1) {
      await categoryStore.getCategory2ListAction(value as number);
      const nodes = categoryStore.category2List.map((item) => ({
        value: item.id,
        label: item.name,
      }));
      resolve(nodes);
    } else if (level === 2) {
      await categoryStore.getCategory3ListAction(value as number);
      const nodes = categoryStore.category3List.map((item) => ({
        value: item.id,
        label: item.name,
        leaf: level >= 2,
      }));
      resolve(nodes);
    }
  },
};
</script>
<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>
